import Vue from 'vue';
import { getDictEnumByCode } from '@/api/system/tbSysDictDefinition';
import { getDictConstByCode } from '@/api/system/tbSysDictDefinition';
export const dictMixins = {
	data() {
		return {
			dictData: {},
			screenWidth: 0
		}
	},
	computed: {
		isMobile() {
			return this.screenWidth < 768;
		},
		isPad() {
			return this.screenWidth < 992 && this.screenWidth >= 768;
		}
	},
	created() {
		this.screenWidth = window.innerWidth;
		window.addEventListener('resize', () => {
			this.screenWidth = window.innerWidth;
		});
		if (!!this.$options.enums) {
			this.getDictDatas(this.$options.enums, 'enum');
		}
		if (!!this.$options.consts) {
			this.getDictDatas(this.$options.consts, 'const');
		}
	},
	methods: {
		//获取字典数据
		async getDictDetail(code, type) {
			let result = null;
			let dictValue = null;
			if (type === 'enum') {
				result = await getDictEnumByCode({ code }).then(res => res.data);
				dictValue = result.code === '0' && result.data || [];
			} else if (type === 'const') {
				result = await getDictConstByCode({ code }).then(res => res.data);
				dictValue = result.code === '0' && Vue.prototype.$detailData(result.data);
			}
			return Promise.resolve({ code, value: dictValue });
		},

		async getDictDatas(arr, type) {
			let promiseArr = arr.map(code => {
				return !!code && this.getDictDetail(code, type);
			});
			let dictArr = await Promise.all(promiseArr);
			dictArr.forEach(item => {
				this.$set(this.dictData, item.code, item.value);
			});
		}
	}
}